<template>
  <div class="app-container">
    <el-image-viewer
      v-if="showImageViewer"
      :on-close="() => { this.showImageViewer = false }"
      :url-list="images"/>
    <div class="app-content-container">
      <grid-table ref="gridTable"
                  ref-form="searchForm"
                  name="WxFans"
                  :loading.sync="loading"
                  :query="query"
                  :perfect="false"
                  :buttons.sync="buttons"
                  :table-id="3"
                  :data="tableData"
                  :slot-column="slotColumn"
                  @remote-method="getUserList">
        <template v-slot:form>
          <vxe-form ref="searchForm" class="inline-form" :data="query" title-align="left" prevent-submit title-colon>
            <vxe-form-item title="OpenId" field="openId">
              <vxe-input v-model="query.openId" placeholder="请输入用户openid" clearable @change="getUserList"/>
            </vxe-form-item>
            <vxe-form-item title="关注渠道" field="status">
              <template v-slot>
                <vxe-select v-model="query.status" placeholder="请选择" clearable>
                  <vxe-option v-for="item in statusOptions" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue" />
                </vxe-select>
              </template>
            </vxe-form-item>
            <vxe-form-item title="关注时间" field="subDateRange">
              <template v-slot>
                <date-picker :value.sync="query.subDateRange"/>
              </template>
            </vxe-form-item>
          </vxe-form>
        </template>
      </grid-table>
    </div>
    <vxe-modal title="用户消息"
               v-model="open"
               :z-index="100"
               :esc-closable="true"
               transfer
               show-footer
               lock-view
               lock-scroll
               destroy-on-close
               width="480"
               height="460"
               resize>
      <WxMsg :wxUserId="wxUserId"/>
    </vxe-modal>
  </div>
</template>

<script>
  import GridTable from "@/components/GridTable/index";
  import DatePicker from "@/components/DatePicker/index";
  import {checkPermit, checkRole } from "@/utils/permission"
  import { getList as listUser, synchroWxUser, updateRemark, tagging } from '@/api/wxmp/user'
  import { getList as listUserTags } from '@/api/wxmp/usertags'
  import WxMsg from '@/components/wx-msg/main'
  import ElImageViewer from 'element-ui/packages/image/src/image-viewer'


  export default {
    name: 'Fans',
    components: { WxMsg, GridTable, DatePicker, ElImageViewer },
    data() {
      return {
        loading: false,
        open: false,
        showImageViewer: false,
        images: [],
        query: {
          pageNum: 1,
          pageSize: 20,
          total: 0,
          openId: undefined,
          subDateRange: []
        },
        tableData: [],
        tableColumns: [
          { title: '用户头像', width: 80, align: "center", field: "headimgUrl", type: "html",
            formatter: ({ cellValue  }) => {
              return `<img src="${cellValue}" width="64"/>`
            }
          },
          { title: 'OpenId', width: 100, field: 'openId', headerAlign: 'center' },
          { title: '昵称', width: 120, field: 'nickName', headerAlign: 'center'},
          { title: '创建时间', width: 150, field: 'createTime', headerAlign: 'center', align: 'center'},
          { title: '关注时间', width: 150, field: 'subscribeTime', headerAlign: 'center', align: 'center'},
          { title: '性别', width: 50, field: 'sex', headerAlign: 'center', align: 'center'},
          { title: '城市', width: 100, field: 'city', headerAlign: 'center', align: 'center'},
          { title: '省份', width: 120, field: "province", headerAlign: 'center', align: 'center' },
          { title: '国家', width: 120, field: "country", headerAlign: 'center', align: 'center' },
          { title: '关注状态', width: 100, field: "subscribe", headerAlign: 'center', align: 'center' },
          { title: '关注次数', width: 100, field: "subscribeNum", align: "center" },
          { title: '关注渠道', width: "auto", field: "subscribeScene", align: "center"}
        ],
        paramsSearch: {},
        tableLoading: false,
        selectionData: [],
        dialogTagging: false,
        checkedTags: [],
        userTagsData: [],
        taggingType: '',
        dialogMsgVisible: false,
        wxUserId: '',
        buttons: [
          { type: 'search' },
          { type: 'edit', click: this.handleEdit, permit: 'sku:article:edit' },
          { type: 'sync', name: '同步' }
        ],
        slotColumn: {
          avatar: {
            default: ({ row }) => {
              return [
                <el-image style="cursor:pointer;width: 64px; height: 64px" src={row.avatar} fit="contain" lazy nativeOnClick={ () => { this.viewImage(row) } }></el-image>
              ]
            }
          },
          mobile: {
            default: ({ row }) => {
              return [
                <span>{row.member.mobile}</span>
              ]
            }
          }
        }
      }
    },
    created() {
        this.getUserList();
    },
    mounted: function () {
    },
    computed: {
        permissionList() {
            return {
                addBtn: checkPermit(['wxmp:user:fans:add']),
                delBtn: checkPermit(['wxmp:user:fans:del']),
                editBtn: checkPermit(['wxmp:user:fans:edit']),
                viewBtn: checkPermit(['wxmp:user:fans:get'])
            }
        }
    },
    methods: {
      viewImage(row) {
        this.images = [row.avatar]
        this.showImageViewer = true
      },
      getUserList() {
        this.loading = true;
        listUser(this.query).then(response => {
          this.tableData = response.rows;
          this.query.total = response.total;
          this.loading = false;
        })
      },
      listUserTags() {
          this.loading = true
          listUserTags().then(response => {
              if (response.code === 200) {
                  let userTagsData = response.data
                  this.userTagsData = userTagsData
                  this.$refs.crud.DIC.tagidList = userTagsData
              } else {
                  this.$message.error('获取用户标签出错：' + response.msg)
              }
              this.tableLoading = false
              this.getPage(this.page)
          }).catch(() => {
              this.tableLoading = false
              this.getPage(this.page)
          })
      },
      wxMsgDo(row) {
          this.wxUserId = row.id
          this.dialogMsgVisible = true
      },
      toTagging() {
          let openIdList = []
          for (let i = 0; i < this.selectionData.length; i++) {
              openIdList.push(this.selectionData[i].openId)
          }
          if (this.checkedTags.length <= 0) {
              this.$message.error('请选择标签')
              return
          }
          if (openIdList.length <= 0) {
              this.$message.error('请选择用户')
              return
          }
          this.tableLoading = true
          tagging({
              taggingType: this.taggingType,
              tagIds: this.checkedTags,
              openIds: openIdList
          }).then(response => {
              this.tableLoading = false
              this.checkedTags = []
              this.$refs.crud.selectClear()
              if (response.code === 200) {
                  this.getPage(this.page)
              } else {
                  this.$message.error('打标签出错：' + response.msg)
              }
          }).catch(() => {
              this.tableLoading = false
          })
          this.dialogTagging = false
      },
      selectionChange(list) {
          this.selectionData = list
      },
      searchChange(params, done) {
          params = this.filterForm(params)
          this.paramsSearch = params
          this.page.currentPage = 1
          this.getPage(this.page, params)
          done()
      },
      synchroWxUser() {
          this.$confirm('同步用户需要一定时间，用户量越大、用时越久，请耐心等待，勿重复提交；确认此操作吗?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
          }).then(() => {
              this.tableLoading = true
              synchroWxUser().then(response => {
                  this.tableLoading = false
                  if (response.code === 200) {
                      this.getPage(this.page)
                  } else {
                      this.$message.error('同步微信用户出错：' + response.msg)
                  }
              }).catch(() => {
                  this.tableLoading = false
              })
              setTimeout(() => {
                  if (this.tableLoading) {
                      this.tableLoading = false
                      this.$alert('同步请求发送成功，系统正在处理中，请稍后刷新查看同步结果，用户量越大用时越久，请耐心等待，勿重复提交', '提示', {
                          confirmButtonText: '确定'
                      })
                  }
              }, 3000)
          }).catch(() => {
          })
      },
      sortChange(val) {
          let prop = val.prop ? val.prop.replace(/([A-Z])/g, "_$1").toLowerCase() : '';
          if (val.order === 'ascending') {
              this.page.descs = []
              this.page.ascs = prop
          } else if (val.order === 'descending') {
              this.page.ascs = []
              this.page.descs = prop
          } else {
              this.page.ascs = []
              this.page.descs = []
          }
          this.getPage(this.page)
      },
      getPage(page, params) {
          this.tableLoading = true
          getPage(Object.assign({
              current: page.currentPage,
              size: page.pageSize,
              descs: this.page.descs,
              ascs: this.page.ascs,
              appType: '2'
          }, params, this.paramsSearch)).then(response => {
              this.tableData = response.data.records
              this.page.total = response.data.total
              this.page.currentPage = page.currentPage
              this.page.pageSize = page.pageSize
              this.tableLoading = false
          }).catch(() => {
              this.tableLoading = false
          })
      },
      updateRemark(row, index) {
          this.$prompt('请输入备注', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              inputPattern: /\S/,
              inputErrorMessage: '输入不能为空'
          }).then(({value}) => {
              this.tableLoading = true
              row.remark = value
              updateRemark(row).then(response => {
                  this.tableLoading = false
                  if (response.code === 200) {
                      this.tableData.splice(index, 1, Object.assign({}, row))
                      this.$message({
                          showClose: true,
                          message: '修改成功',
                          type: 'success'
                      })
                      this.getPage(this.page)
                  } else {
                      this.$message.error(response.msg)
                  }
              }).catch(() => {
                  this.tableLoading = false
              })
          })
      },
      handleDel: function (row, index) {
          var _this = this
          this.$confirm('是否确认删除', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
          }).then(function () {
              return delObj(row.id)
          }).then(data => {
              _this.msgSuccess('删除成功')
              this.getPage(this.page)
          }).catch(function (err) {
          })
      },
      /**
       * @title 数据更新
       * @param row 为当前的数据
       * @param index 为当前更新数据的行数
       * @param done 为表单关闭函数
       *
       **/
      handleUpdate: function (row, index, done, loading) {
          putObj(row).then(data => {
              this.$message({
                  showClose: true,
                  message: '修改成功',
                  type: 'success'
              })
              done()
              this.getPage(this.page)
          }).catch(() => {
              loading()
          })
      },
      /**
       * @title 数据添加
       * @param row 为当前的数据
       * @param done 为表单关闭函数
       *
       **/
      handleSave: function (row, done, loading) {
          addObj(row).then(data => {
              this.$message({
                  showClose: true,
                  message: '添加成功',
                  type: 'success'
              })
              done()
              this.getPage(this.page)
          }).catch(() => {
              loading()
          })
      },
      /**
       * 刷新回调
       */
      refreshChange(page) {
          this.getPage(page)
      }
    }
  }
</script>

<style lang="scss" scoped>

</style>
